/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.delivery.service.impl.DeliveryRuleServiceImpl
   Module Description   :

   Date Created      : 2010/12/15
   Original Author   : feeling.wang
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.delivery.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.common.utils.StringUtils;
import com.yaodian100.ec.delivery.entity.DeliveryRule;
import com.yaodian100.ec.delivery.entity.ViewDeliveryRule;
import com.yaodian100.ec.delivery.service.DeliveryRuleService;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.order.entity.Orders.ORDER_LOGISTIC_PROVIDER_TP;
import com.yaodian100.ec.order.service.OrderService;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.service.Product2Service;
import com.yaodian100.ec.shopping.service.CartOrdersService;

/**
 * @author feeling.wang
 * 
 */
public class DeliveryRuleServiceImpl extends DomainServiceImpl<DeliveryRule> implements DeliveryRuleService {
	// private ObjectDao<OtherDeliveryRule> otherDeliveryRuleDao;
	private final static String CART_TABLE = "ec_cart_order_product";
	private final static String ORDER_TABLE = "ec_order_product";
	private final static String CART_ID = "cart_id";
	private final static String ORDER_ID = "order_id";
	private final static String DEFAULT_FROM_PROVINCE = "上海";
	// private final static String DEFAULT_FROM_CITY = "上海市";
	@Autowired
	private OrderService orderService;
	@Autowired
	private BaseManager baseMgr;
	@Autowired
	private CartOrdersService cartOrdersService;
	@Autowired
	private Product2Service product2Service;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#getCitys(java.lang.String, java.lang.String)
	 */
	/**
	 * 依商品型态、省-查询递送的城市范围
	 * 
	 * @param type CART or ORDER
	 * @param id CARTID or ORDERID
	 * @param toProvince
	 * @return
	 */
	Map<String, String> getCitys(String type, String id, String toProvince) {
		return this.getCitys(type, id, toProvince, false);
	}

	Map<String, String> getCitys(String type, String id, String toProvince, boolean onlyCOD) {
		Map<String, String> deliveryTypeMap = findDeliveryType(type, id);
		String deliveryType = deliveryTypeMap.get("deliveryType");
		StringBuffer sb = new StringBuffer();
		List<String> attrs = new ArrayList<String>();
		sb.append("select distinct d.toCity,d.version from DeliveryRule d ");
		// 大材積運送配置
		Map<String, String> prodVolumeMap = new HashMap<String, String>();
		if (StringUtils.equalsIgnoreCase("cart", type)) {
			prodVolumeMap = cartOrdersService.chkVolumeOfCartOrderDetail(id);
		} else if (StringUtils.equalsIgnoreCase("order", type)) {
			prodVolumeMap = orderService.chkVolumeOfOrderDetail(id);
		}
		if (prodVolumeMap.size() > 0) {
			sb.append(",OtherDeliveryRule o ");
			sb.append("where d.toCity = o.toCity and ");
		} else {
			sb.append("where ");
		}
		sb.append("d.toProvince = '").append(toProvince).append("' ");
		if (StringUtils.equalsIgnoreCase(ServerValue.getScmType(), deliveryType)) {
			String fromProvince = deliveryTypeMap.get("fromProvince");
			String[] provinces = fromProvince.split(",");
			int i = 0;
			sb.append("and d.fromProvince in (");
			for (String p : provinces) {
				sb.append("'").append(p).append("'");
				if (i != provinces.length - 1) {
					sb.append(" , ");
				}
				i++;
			}
			sb.append(" ) ");
			sb.append("and d.service = '10' ");// 轉單商品固定只找10
		} else {
			sb.append("and d.fromProvince = '").append(DEFAULT_FROM_PROVINCE).append("' ");
		}
		sb.append("and d.type = '").append(deliveryType).append("' ");
		// 手机限制COD, POS
		if (onlyCOD) {
			sb.append("and (d.service = '20' or d.service = '30') ");
		}

		List<Object> citys = getDao().getQueryByList(sb.toString(), attrs, 0, -1);
		Map<String, String> citysMap = new HashMap<String, String>();
		citysMap = ArrayUtils.toMap(citys.toArray());
		return citysMap;
	}

	/**
	 * 判斷傳入的是要查購物車商品or訂單商品
	 * 
	 * @param type
	 * @param id
	 * @return
	 */
	public Map<String, String> findDeliveryType(String type, String id) {
		StringBuffer sb = new StringBuffer();
		String deliveryType = ServerValue.getNmlType();
		String searchTable = "";
		String searchField = "";
		if (StringUtils.equalsIgnoreCase("cart", type)) {// 查購物車
			searchTable = CART_TABLE;
			searchField = CART_ID;
		} else {
			searchTable = ORDER_TABLE;
			searchField = ORDER_ID;
		}
		sb.append("select p.product_type,p.is_scm,sa.supplier_id,sa.shipprovince,sa.shipcity,sa.shiparea,sa.isselfship ");
		sb.append("from ec_product_main p,ec_supplier_apply sa ");
		sb.append("where p.supplier_id = sa.supplier_id ");
		if (Arrays.asList("cart", "order").contains(type)) {
			sb.append("and p.product_id in ( ");
			sb.append("select prod_id from ").append(searchTable);
			sb.append(" where prod_tp != 2 and ");
			sb.append(searchField).append(" = ? ) ");
		} else {
			sb.append("and p.product_id = ? ");
		}
		List<Object> attrs = new ArrayList<Object>();
		attrs.add(id);
		List<Object> objs = getDao().getSQLQueryByList(sb.toString(), attrs, 0, -1);
		String pdtTypes = "";
		String pdtScms = "";
		Map<String, String> resultMap = new HashMap<String, String>();
		StringBuffer supplierId = new StringBuffer();
		StringBuffer fromProvince = new StringBuffer();
		StringBuffer fromCity = new StringBuffer();
		StringBuffer fromDistrict = new StringBuffer();
		StringBuffer isselfship = new StringBuffer();
		for (Object obj : objs) {
			Object pdts[] = (Object[]) obj;
			pdtTypes = pdtTypes + pdts[0];
			pdtScms = pdtScms + pdts[1];
			if (StringUtils.equalsIgnoreCase("Y", pdts[1].toString())
					&& Arrays.asList("0", "1", "6").contains(pdts[0].toString())) {
				// 轉單且為主商品含N選M(0或1或6),記錄供應商資料
				supplierId.append(pdts[2].toString()).append(",");
				fromProvince.append(pdts[3].toString()).append(",");
				fromCity.append(null != pdts[4] ? pdts[4].toString() : "").append(",");
				fromDistrict.append(null != pdts[5] ? pdts[5].toString() : "").append(",");
				isselfship.append(null != pdts[6] ? pdts[6].toString() : "");
			}
		}
		if (supplierId.length() > 0) {// 轉單且為主商品含N選M(0或1或6),記錄供應商資料
			resultMap.put("supplierId", supplierId.toString());
			// 供应商自行配送
			int count = org.apache.commons.lang.StringUtils.countMatches(isselfship.toString(), "Y");
			// System.out.println("count:" + count);
			// System.out.println("isselfship.toString():" + isselfship.toString());
			// System.out.println("isselfship.toString().length():" + isselfship.toString().length());
			if (count == 0 || isselfship.toString().length() != count) {// 含有非自配送的供應商
				resultMap.put("fromProvince", fromProvince.toString());
			} else {// 自配送的供應商皆由上海發貨(default)
				resultMap.put("fromProvince", DEFAULT_FROM_PROVINCE);
			}
			resultMap.put("fromCity", fromCity.toString());
			resultMap.put("fromDistrict", fromDistrict.toString());
		}
		if (!StringUtils.equalsIgnoreCase("serviceOrder", type)) {// 退換貨地址不需要判斷物流配送地址
			if (StringUtils.contains(pdtTypes, "7")) {// 精品
				deliveryType = ServerValue.getLuxType();
			} else {
				if (StringUtils.contains(pdtScms, "Y")) {// 轉單
					deliveryType = ServerValue.getScmType();
				} else if (!chkProdDetailCanUseCod(type, id)) {
					deliveryType = ServerValue.getLuxType();
				}
			}
		}
		resultMap.put("deliveryType", deliveryType);
		resultMap.put("type", type);
		resultMap.put("typeId", id);
		supplierId.setLength(0);
		fromProvince.setLength(0);
		fromCity.setLength(0);
		fromDistrict.setLength(0);
		isselfship.setLength(0);
		return resultMap;
	}

	/**
	 * 依商品型态、省、城市-查询递送的地区范围
	 * 
	 * @param type
	 * @param toProvince
	 * @param toCity
	 * @return
	 */
	List<ViewDeliveryRule> getDistricts(String type, String id, String toCity) {
		Map<String, String> deliveryTypeMap = findDeliveryType(type, id);
		// String deliveryType = deliveryTypeMap.get("deliveryType");
		// String fromProvince = deliveryTypeMap.get("fromProvince");
		// String fromCity = deliveryTypeMap.get("fromCity");
		// String fromDistrict = deliveryTypeMap.get("fromDistrict");
		List<ViewDeliveryRule> districts = new ArrayList<ViewDeliveryRule>();
		districts = getViewDeliveryRuleList(deliveryTypeMap, "", toCity, "");
		return districts;
	}

	public List<ViewDeliveryRule> getViewDeliveryRuleList(Map<String, String> deliveryTypeMap, String toProvince,
			String toCity, String toDistrict) {
		StringBuffer sb = new StringBuffer();
		List<String> attrs = new ArrayList<String>();
		sb.append("SELECT D.TYPE,D.TO_PROVINCE,D.TO_CITY,D.TO_DISTRICT,");
		sb.append("to_char(substr(wmsys.wm_concat(DISTINCT D.SERVICE),1,20)) SERVICES,");
		sb.append("D.VERSION FROM EC_DELIVERY_RULE D ");

		// 大材積運送配置
		Map<String, String> prodVolumeMap = new HashMap<String, String>();
		if (StringUtils.equalsIgnoreCase("cart", deliveryTypeMap.get("type"))) {
			prodVolumeMap = cartOrdersService.chkVolumeOfCartOrderDetail(deliveryTypeMap.get("typeId"));
		} else if (StringUtils.equalsIgnoreCase("order", deliveryTypeMap.get("type"))) {
			prodVolumeMap = orderService.chkVolumeOfOrderDetail(deliveryTypeMap.get("typeId"));
		}
		if (prodVolumeMap.size() > 0) {
			sb.append(",EC_OTHER_DELIVERY_RULE O ");
			sb.append("where D.TO_DISTRICT = O.TO_DISTRICT ");
		} else {
			sb.append("where 1 = 1 ");
		}
		if (StringUtils.isNotBlank(toDistrict)) {
			sb.append("and D.TO_DISTRICT = ? ");
			attrs.add(toDistrict);
		}
		if (StringUtils.isNotBlank(toCity)) {
			sb.append("and D.TO_CITY = ? ");
			attrs.add(toCity);
		}
		if (StringUtils.isNotBlank(toProvince)) {
			sb.append("and D.TO_PROVINCE = ? ");
			attrs.add(toProvince);
		}
		if (StringUtils.equalsIgnoreCase(ServerValue.getScmType(), deliveryTypeMap.get("deliveryType"))) {
			// if (StringUtils.isNotBlank(deliveryTypeMap.get("fromCity"))) {
			// sb.append("and D.FROM_CITY = ? ");
			// attrs.add(deliveryTypeMap.get("fromCity"));
			// }
			// if (StringUtils.isNotBlank(deliveryTypeMap.get("fromDistrict"))) {
			// sb.append("and D.FROM_DISTRICT = ? ");
			// attrs.add(deliveryTypeMap.get("fromDistrict"));
			// }
			String fromProvince = deliveryTypeMap.get("fromProvince");
			String[] provinces = fromProvince.split(",");
			int i = 0;
			sb.append("and D.FROM_PROVINCE in ( ");
			for (String p : provinces) {
				sb.append("'").append(p).append("'");
				if (i != provinces.length - 1) {
					sb.append(" , ");
				}
				i++;
			}
			sb.append(" ) ");
			sb.append("and D.SERVICE = '10' ");
		} else {
			sb.append("and D.FROM_PROVINCE = ? ");
			attrs.add(DEFAULT_FROM_PROVINCE);
		}
		sb.append("and D.TYPE = ? ");
		attrs.add(deliveryTypeMap.get("deliveryType"));
		sb.append("GROUP BY D.TYPE,D.TO_PROVINCE,D.TO_CITY,D.TO_DISTRICT,");
		sb.append("D.VERSION");
		// sb.append("GROUP BY D.TYPE,D.FROM_PROVINCE,D.FROM_CITY,D.FROM_DISTRICT,D.TO_PROVINCE,D.TO_CITY,D.TO_DISTRICT,");
		// sb.append("D.VERSION");

		List vdrs = getDao().getSQLQueryByList(sb.toString(), attrs, 0, -1);

		List<ViewDeliveryRule> lists = new ArrayList<ViewDeliveryRule>();
		ViewDeliveryRule vdr2 = null;
		if (null != vdrs && !vdrs.isEmpty()) {
			for (int i = 0; i < vdrs.size(); i++) {
				Object[] obj = (Object[]) vdrs.get(i);
				vdr2 = new ViewDeliveryRule();
				vdr2.setType(obj[0].toString());
				// vdr2.setFromProvince(null != obj[1] ? obj[1].toString() : "");
				// vdr2.setFromCity(null != obj[2] ? obj[2].toString() : "");
				// vdr2.setFromDistrict(null != obj[3] ? obj[3].toString() : "");
				vdr2.setToProvince(null != obj[1] ? obj[1].toString() : "");
				vdr2.setToCity(null != obj[2] ? obj[2].toString() : "");
				vdr2.setToDistrict(null != obj[3] ? obj[3].toString() : "");
				vdr2.setIsShip(null != obj[4] ? StringUtils.contains(obj[4].toString(), "10") ? "Y" : "N" : "");
				vdr2.setIsCod(null != obj[4] ? StringUtils.contains(obj[4].toString(), "20") ? "Y" : "N" : "");
				vdr2.setIsPos(null != obj[4] ? StringUtils.contains(obj[4].toString(), "30") ? "Y" : "N" : "");
				vdr2.setVersion(null != obj[5] ? obj[5].toString() : "");
				lists.add(vdr2);
			}
		}
		return lists;
	}

	// public List<ViewDeliveryRule> getViewDeliveryRuleList(String deliveryType, String fromProvince, String fromCity,
	// String fromDistrict, String toProvince, String toCity, String toDistrict) {
	// StringBuffer sb = new StringBuffer();
	// List<String> attrs = new ArrayList<String>();
	// sb.append("SELECT TYPE,FROM_PROVINCE,FROM_CITY,FROM_DISTRICT,TO_PROVINCE,TO_CITY,TO_DISTRICT,");
	// sb.append("to_char(substr(wmsys.wm_concat(DISTINCT SERVICE),1,20)) SERVICES,");
	// sb.append("VERSION FROM EC_DELIVERY_RULE ");
	// sb.append("where 1 = 1 ");
	// if (StringUtils.isNotBlank(toDistrict)) {
	// sb.append("and TO_DISTRICT = ? ");
	// attrs.add(toDistrict);
	// }
	// if (StringUtils.isNotBlank(toCity)) {
	// sb.append("and TO_CITY = ? ");
	// attrs.add(toCity);
	// }
	// if (StringUtils.isNotBlank(toProvince)) {
	// sb.append("and TO_PROVINCE = ? ");
	// attrs.add(toProvince);
	// }
	// if (StringUtils.equalsIgnoreCase(ServerValue.getScmType(), deliveryType)) {
	// if (StringUtils.isNotBlank(fromCity)) {
	// sb.append("and FROM_CITY = ? ");
	// attrs.add(fromCity);
	// }
	// if (StringUtils.isNotBlank(fromDistrict)) {
	// sb.append("and FROM_DISTRICT = ? ");
	// attrs.add(fromDistrict);
	// }
	// sb.append("and FROM_PROVINCE = ? ");
	// attrs.add(fromProvince);
	// } else {
	// sb.append("and FROM_PROVINCE = ? ");
	// attrs.add(DEFAULT_FROM_PROVINCE);
	// }
	// sb.append("and TYPE = ? ");
	// attrs.add(deliveryType);
	// sb.append("GROUP BY TYPE,FROM_PROVINCE,FROM_CITY,FROM_DISTRICT,TO_PROVINCE,TO_CITY,TO_DISTRICT,");
	// sb.append("VERSION");
	//
	// List vdrs = getDao().getSQLQueryByList(sb.toString(), attrs, 0, -1);
	//
	// List<ViewDeliveryRule> lists = new ArrayList<ViewDeliveryRule>();
	// ViewDeliveryRule vdr2 = null;
	// if (null != vdrs && !vdrs.isEmpty()) {
	// for (int i = 0; i < vdrs.size(); i++) {
	// Object[] obj = (Object[]) vdrs.get(i);
	// vdr2 = new ViewDeliveryRule();
	// vdr2.setType(obj[0].toString());
	// vdr2.setFromProvince(null != obj[1] ? obj[1].toString() : "");
	// vdr2.setFromCity(null != obj[2] ? obj[2].toString() : "");
	// vdr2.setFromDistrict(null != obj[3] ? obj[3].toString() : "");
	// vdr2.setToProvince(null != obj[4] ? obj[4].toString() : "");
	// vdr2.setToCity(null != obj[5] ? obj[5].toString() : "");
	// vdr2.setToDistrict(null != obj[6] ? obj[6].toString() : "");
	// vdr2.setIsShip(null != obj[7] ? StringUtils.contains(obj[7].toString(), "10") ? "Y" : "N" : "");
	// vdr2.setIsCod(null != obj[7] ? StringUtils.contains(obj[7].toString(), "20") ? "Y" : "N" : "");
	// vdr2.setIsPos(null != obj[7] ? StringUtils.contains(obj[7].toString(), "30") ? "Y" : "N" : "");
	// vdr2.setVersion(null != obj[8] ? obj[8].toString() : "");
	// lists.add(vdr2);
	// }
	// }
	// return lists;
	// }

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#getCartCitys(java.lang.String, java.lang.String)
	 */
	@Override
	public Map<String, String> getCartCitys(String id, String toProvince) {
		return getCitys("cart", id, toProvince);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#getCartDistricts(java.lang.String, java.lang.String)
	 */
	@Override
	public List<ViewDeliveryRule> getCartDistricts(String id, String toCity) {
		return getDistricts("cart", id, toCity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#getOrderCitys(java.lang.String, java.lang.String)
	 */
	@Override
	public Map<String, String> getOrderCitys(String id, String toProvince) {
		return getCitys("order", id, toProvince);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#getOrderDistricts(java.lang.String, java.lang.String)
	 */
	@Override
	public List<ViewDeliveryRule> getOrderDistricts(String id, String toCity) {
		return getDistricts("order", id, toCity);
	}

	@Override
	public Map<String, String> getMobileCartCitys(String id, String toProvince) {
		return getCitys("cart", id, toProvince, true);
	}

	Map<String, String> getProvinces(String type, String id) {
		Map<String, String> deliveryTypeMap = findDeliveryType(type, id);
		String deliveryType = deliveryTypeMap.get("deliveryType");
		String fromProvince = deliveryTypeMap.get("fromProvince");
		StringBuffer sb = new StringBuffer();
		List<String> attrs = new ArrayList<String>();
		sb.append("select distinct d.toProvince,d.version from DeliveryRule d ");
		// 大材積運送配置
		Map<String, String> prodVolumeMap = new HashMap<String, String>();
		if (StringUtils.equalsIgnoreCase("cart", type)) {
			prodVolumeMap = cartOrdersService.chkVolumeOfCartOrderDetail(id);
		} else if (StringUtils.equalsIgnoreCase("order", type)) {
			prodVolumeMap = orderService.chkVolumeOfOrderDetail(id);
		} else if (StringUtils.equalsIgnoreCase("product", type)) {
			boolean result = product2Service.chkVolumeOfProduct(id);
			if (result) {
				Product product = (Product) baseMgr.get(Product.class, id);
				prodVolumeMap.put(id, product.getProductName());
			}
		}

		if (prodVolumeMap.size() > 0) {
			sb.append(",OtherDeliveryRule o ");
			sb.append("where d.toProvince = o.toProvince and ");
		} else {
			sb.append("where ");
		}

		if (StringUtils.equalsIgnoreCase(ServerValue.getScmType(), deliveryType)) {
			String[] provinces = fromProvince.split(",");
			int i = 0;
			sb.append("d.fromProvince in ( ");
			for (String p : provinces) {
				sb.append("'").append(p).append("'");
				if (i != provinces.length - 1) {
					sb.append(" , ");
				}
				i++;
			}
			sb.append(" ) ");
			sb.append("and d.service = '10' ");// 轉單商品固定只找10
		} else {
			sb.append("d.fromProvince = ? ");
			attrs.add(DEFAULT_FROM_PROVINCE);
		}
		sb.append(" and d.type = ? ");
		attrs.add(deliveryType);
		List<Object> provinces = getDao().getQueryByList(sb.toString(), attrs, 0, -1);
		Map<String, String> provincesMap = new HashMap<String, String>();
		provincesMap = ArrayUtils.toMap(provinces.toArray());
		return provincesMap;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#getCartProvinces(java.lang.String)
	 */
	@Override
	public Map<String, String> getCartProvinces(String id) {
		return getProvinces("cart", id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#getOrderProvinces(java.lang.String)
	 */
	@Override
	public Map<String, String> getOrderProvinces(String id) {
		return getProvinces("order", id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#canUseCod(java.lang.String)
	 */
	@Override
	public ViewDeliveryRule canUseCodByOrderId(String id) {
		Orders order = orderService.get(id);
		Map<String, String> deliveryTypeMap = findDeliveryType("order", id);
		// String deliveryType = deliveryTypeMap.get("deliveryType");
		// String fromProvince = deliveryTypeMap.get("fromProvince");
		// String fromCity = deliveryTypeMap.get("fromCity");
		// String fromDistrict = deliveryTypeMap.get("fromDistrict");
		List<ViewDeliveryRule> vdrs = getViewDeliveryRuleList(deliveryTypeMap, order.getReceiverProvince(), order
				.getReceiverCity(), order.getReceiverArea());
		if (null != vdrs && vdrs.size() > 0) {
			return vdrs.get(0);
		}
		return null;
	}

	DeliveryRule getDeliveryRule(String type, String id, String toProvince, String toCity, String toDistrict,
			String service) {
		Map<String, String> deliveryTypeMap = findDeliveryType(type, id);
		String deliveryType = deliveryTypeMap.get("deliveryType");
		String fromProvince = deliveryTypeMap.get("fromProvince");
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("service", service);
		crit.addEq("toDistrict", toDistrict);
		crit.addEq("toCity", toCity);
		crit.addEq("toProvince", toProvince);
		if (StringUtils.equalsIgnoreCase(ServerValue.getScmType(), deliveryType)) {
			String[] provinces = fromProvince.split(",");
			crit.addIn("fromProvince", Arrays.asList(provinces));
			crit.addEq("service", "10");// 轉單商品固定只找10
		} else {
			crit.addEq("fromProvince", DEFAULT_FROM_PROVINCE);
		}
		crit.addEq("type", deliveryType);
		List<DeliveryRule> lists = getDao().getList(crit, null);
		if (null != lists && !lists.isEmpty()) {
			return lists.get(0);
		} else {
			return null;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#getDeliveryRule(java.lang.String, java.lang.String,
	 * java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public DeliveryRule getCartDeliveryRule(String id, String toProvince, String toCity, String toDistrict, String service) {
		return getDeliveryRule("cart", id, toProvince, toCity, toDistrict, service);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#findDaphneAddress()
	 */
	@Override
	public String findAddressVersion() {
		Object[] versions = baseMgr.queryByHql("SELECT version FROM DeliveryRule WHERE rownum < 2", new Object[] {});
		if (null != versions && !ArrayUtils.isEmpty(versions)) {
			return versions[0].toString();
		} else {
			return "";
		}
	}

	public String findAddressVersion(Orders order) {
		Map<String, String> deliveryTypeMap = findDeliveryType("order", order.getOrderId());
		String deliveryType = deliveryTypeMap.get("deliveryType");
		String fromProvince = ServerValue.getScmType().equalsIgnoreCase(deliveryType) ? deliveryTypeMap.get("fromProvince")
				: "上海";
		deliveryTypeMap.put("fromProvince", fromProvince);
		String version = "";
		List<ViewDeliveryRule> vdrs = getViewDeliveryRuleList(deliveryTypeMap, order.getReceiverProvince(), order
				.getReceiverCity(), order.getReceiverArea());
		if (null != vdrs && !vdrs.isEmpty()) {
			version = vdrs.get(0).getVersion();
		}
		return version;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.shopping.service.CartOrdersService#canUseCod(java.lang.String)
	 */
	@Override
	public boolean chkProdDetailCanUseCod(String type, String id) throws CoreException {
		StringBuffer sb = new StringBuffer();
		List<String> attrs = new ArrayList<String>();
		sb.append("select count(*) from ec_product_main where product_id in ( ");
		if (StringUtils.equalsIgnoreCase("cart", type)) {// 查購物車
			sb.append("select prod_id from ec_cart_order_detail where cart_id= ? ");
		} else if (StringUtils.equalsIgnoreCase("order", type)) {// 查訂單
			sb.append("select prod_id from ec_order_detail where order_id= ? ");
		} else {
			sb.append(" ? ");
		}
		sb.append(") and ( can_use_cod = 'N' or is_scm = 'Y' ) ");
		attrs.add(id);
		List list = getDao().getSQLQueryByList(sb.toString(), attrs, 0, -1);
		if (Integer.parseInt(list.get(0).toString()) > 0) {
			return false;
		} else {
			return true;
		}
	}

	public Map<String, String> cartDetailCanUseCodMap(String id) throws CoreException {
		return detailCanUseCodMap("cart", id);
	}

	public Map<String, String> orderDetailCanUseCodMap(String id) throws CoreException {
		return detailCanUseCodMap("order", id);
	}

	Map<String, String> detailCanUseCodMap(String type, String id) throws CoreException {
		StringBuffer sb = new StringBuffer();
		List<String> attrs = new ArrayList<String>();
		sb.append("select product_id,product_type,can_use_cod from ec_product_main where product_id in ( ");
		if (StringUtils.equals("cart", type)) {
			sb.append("select prod_id from ec_cart_order_detail where cart_id= ? ");
		} else {
			sb.append("select prod_id from ec_order_detail where order_id= ? ");
		}
		sb.append(" )");
		attrs.add(id);
		List list = getDao().getSQLQueryByList(sb.toString(), attrs, 0, -1);
		Map<String, String> prodCanUseCodMap = new HashMap<String, String>();
		if (null != list && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Object[] result = (Object[]) list.get(i);
				prodCanUseCodMap.put(result[0].toString(), result[1].toString() + ","
						+ StringUtils.defaultString(result[2].toString(), "Y"));
			}
		}
		return prodCanUseCodMap;
	}

	public String logisticProviderTpByOrderId(String id) throws CoreException {
		Map<String, String> prodCanUseCodMap = orderDetailCanUseCodMap(id);
		return logisticProviderTp(prodCanUseCodMap);
	}

	public String logisticProviderTp(Map<String, String> prodCanUseCodMap) throws CoreException {
		StringBuffer sb = new StringBuffer();
		for (String key : prodCanUseCodMap.keySet()) {
			sb.append(prodCanUseCodMap.get(key));
		}
		String logisticProviderTp = ORDER_LOGISTIC_PROVIDER_TP.DEFAULT_PROVIDER.getValue();
		if (sb.indexOf("7") != -1) {// 精品
			if (sb.indexOf("N") != -1) {// 不可貨到付款
				logisticProviderTp = ORDER_LOGISTIC_PROVIDER_TP.NOT_COD_PROVIDER.getValue();
			} else {// 可貨到付款
				logisticProviderTp = ORDER_LOGISTIC_PROVIDER_TP.COD_PROVIDER.getValue();
			}
		} else {
			if (sb.indexOf("N") != -1) {
				logisticProviderTp = ORDER_LOGISTIC_PROVIDER_TP.NOT_COD_PROVIDER.getValue();
			}
		}
		return logisticProviderTp;
	}

	// public ObjectDao<OtherDeliveryRule> getOtherDeliveryRuleDao() {
	// return otherDeliveryRuleDao;
	// }
	//
	// public void setOtherDeliveryRuleDao(ObjectDao<OtherDeliveryRule> otherDeliveryRuleDao) {
	// this.otherDeliveryRuleDao = otherDeliveryRuleDao;
	// }

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#findOtherDeliveryRuleCitysByProvince(java.lang.String)
	 */
	@Override
	public Object[] findOtherDeliveryRuleCitysByProvince(String province) throws CoreException {
		Object[] citys = baseMgr.queryByHql("select distinct toCity from OtherDeliveryRule where toProvince = ? ",
				new Object[] { province });
		return citys;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#findOtherDeliveryRuleDistrictsByCity(java.lang.String)
	 */
	@Override
	public Object[] findOtherDeliveryRuleDistrictsByCity(String city) throws CoreException {
		Object[] districts = baseMgr.queryByHql("select distinct toDistrict from OtherDeliveryRule where toCity = ? ",
				new Object[] { city });
		return districts;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#findOtherDeliveryRuleProvinces()
	 */
	@Override
	public Object[] findOtherDeliveryRuleProvinces() throws CoreException {
		Object[] provinces = baseMgr.queryByHql("select distinct toProvince from OtherDeliveryRule", new Object[] {});
		return provinces;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#getServiceOrderCitys(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public Map<String, String> getServiceOrderCitys(String id, String toProvince) {
		return getCitys("serviceOrder", id, toProvince);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#getServiceOrderDistricts(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public List<ViewDeliveryRule> getServiceOrderDistricts(String id, String toCity) {
		return getDistricts("serviceOrder", id, toCity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#getServiceOrderProvinces(java.lang.String)
	 */
	@Override
	public Map<String, String> getServiceOrderProvinces(String id) {
		return getProvinces("serviceOrder", id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#getProductProvinces(java.lang.String)
	 */
	@Override
	public Map<String, String> getProductProvinces(String id) {
		return getProvinces("product", id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#getProductDistricts(java.lang.String, java.lang.String)
	 */
	@Override
	public List<ViewDeliveryRule> getProductDistricts(String id, String toCity) {
		return getDistricts("product", id, toCity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#getProductCitys(java.lang.String, java.lang.String)
	 */
	@Override
	public Map<String, String> getProductCitys(String id, String toProvince) {
		return getCitys("product", id, toProvince);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.delivery.service.DeliveryRuleService#getProductDeliveryRule(java.lang.String,
	 * java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public DeliveryRule getProductDeliveryRule(String id, String toProvince, String toCity, String toDistrict,
			String service) {
		return getDeliveryRule("product", id, toProvince, toCity, toDistrict, service);
	}
}